import { createSlice } from "@reduxjs/toolkit"
import cache from "@/utils/cache"
import { getToken, getUserInfo } from "@/api/login"
import message from "@/utils/message"

const loginStore = createSlice({

    name: "loginStore",

    initialState: {
        token: cache.getCache("token") || "",
        userInfo: {}
    },

    reducers: {
        setToken(state, action) {
            state.token = action.payload
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        }
    }

})

// 登录
const loginAction = (loginForm, callback) => {
    return async (dispatch) => {
        const res = await getToken(loginForm)
        if (res?.code == 200) {
            message.success(res.msg)
            cache.setCache("token", res.data.token)
            dispatch(setToken(res.data.token))
            callback(res)
        }
    }
}

// 获取用户信息
const getUserInfoAction = () => {
    return async (dispatch) => {
        const res = await getUserInfo()
        if (res?.code == 200) {
            dispatch(setUserInfo(res.data))
        }
    }
}

const { setToken, setUserInfo } = loginStore.actions

const loginReducer = loginStore.reducer

export { setToken, setUserInfo, loginAction, getUserInfoAction }

export default loginReducer